<?php

/**
 * This is the model class for table "{{pages}}".
 *
 * The followings are the available columns in table '{{pages}}':
 * @property string $pageId
 * @property string $pageParent
 * @property string $pageType
 * @property string $pageUrl
 * @property string $pageTitle
 * @property string $pageContentShort
 * @property string $pageContentFull
 * @property string $pageImages
 * @property integer $pageActive
 * @property string $pageAuthor
 * @property integer $pageSort
 * @property string $pageAction
 * @property integer $pageItemId
 */
class NewModel extends CActiveRecord {

    public $brand;
    public $cat_id;
    public $cat_url;

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{pages}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('pageUrl, pageTitle, pageActive, brand', 'required'),
            array('pageParent', 'default'),
            array('pageImages', 'file', 'allowEmpty' => false, 'types' => 'jpg,png,bmp,jpeg', 'on' => 'create'),
            array('pageImages', 'file', 'allowEmpty' => true, 'types' => 'jpg,png,bmp,jpeg', 'on' => 'update'),
            array('pageUrl', 'unique'),
            array('pageId, pageParent, pageType, pageUrl, pageTitle, pageContentShort, pageContentFull, pageImages, pageActive, pageAuthor, pageSort, pageAction, pageItemId', 'safe', 'on' => 'search'),
        );
    }

    public function getBrands() {

        $array = array();

        $query = 'select b."pageId", (select c."pageTitle" from mb_pages c where c."pageId" =b."pageParent" ) ||  \' > \' || b."pageTitle" as "pageTitle" FROM mb_pages b where b."pageType"=\'brand\'';
        $brands = Yii::app()->db->createCommand($query)->queryAll();

        foreach ($brands as $brand) {
            $array[$brand['pageId']] = $brand['pageTitle'];
        }

        return $array;
    }

    public function getCategoryToBrand($pageParent) {
        $models = Page::model()->findAll("\"pageId\" = '" . (int) $pageParent . "'");
        $str = '';
        foreach ($models as $model) {
            $str .= '"' . $model['pageId'] . '" ,';
        }
        return substr($str, 0, strlen($str) - 1);
    }

    public function getProductCategory() {
        return json_encode(Yii::app()->db->createCommand("SELECT \"pageId\" as id, \"pageTitle\" as title FROM {{pages}} WHERE \"pageType\" = 'category'")->queryAll(true), 1);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'pageId' => 'ID',
            'pageParent' => 'Родительская бренд',
            'pageType' => 'Page Type',
            'pageUrl' => 'Адрес',
            'pageTitle' => 'Название',
            'pageContentShort' => 'Page Content Short',
            'pageContentFull' => 'Page Content Full',
            'pageImages' => 'Изображение',
            'pageActive' => 'Активность',
            'pageAuthor' => 'Page Author',
            'pageCategory' => 'Категория',
            'pageAction' => 'Page Action',
            'brand' => 'Бренд',
        );
    }

    public function getDropdownItems($parentId = 0, $level = 0) {
        $itemsFormatted = array();
        $items = $this->model()->findAllByAttributes(array(
            'pageParent' => $parentId,
            'pageType' => 'brand',
        ));
        foreach ($items as $item) {
            $itemsFormatted[$item->pageId] = str_repeat('&nbsp;&nbsp;', $level) . $item->pageTitle;
            $itemsFormatted = $itemsFormatted + $this->getDropdownItems($item->pageId, $level + 1);
        }
        return $itemsFormatted;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('"pageId"', $this->pageId);
        $criteria->compare('"pageParent"', $this->pageParent, true);
        $criteria->compare('"pageType"', $this->pageType, true);
        $criteria->compare('"pageUrl"', $this->pageUrl, true);
        $criteria->compare('"pageTitle"', $this->pageTitle, true);
        $criteria->compare('"pageContentShort"', $this->pageContentShort, true);
        $criteria->compare('"pageContentFull"', $this->pageContentFull, true);
        $criteria->compare('"pageImages"', $this->pageImages, true);
        $criteria->compare('"pageActive"', $this->pageActive);
        $criteria->compare('"pageAuthor"', $this->pageAuthor, true);
        $criteria->compare('"pageSort"', $this->pageSort);
        $criteria->compare('"pageAction"', $this->pageAction, true);
        $criteria->compare('"pageItemId"', $this->pageItemId);

        $criteria->addCondition("(\"pageType\" = 'brand' OR \"pageType\" = 'model')");
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 20,
                'pageVar' => 'page'
            ),
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Brand the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function beforeSave() {
        if (parent::beforeSave()) {
            if (filter_var($this->pageImages, FILTER_VALIDATE_URL)) {
                if (getimagesize($this->pageImages)) {
                    $image = str_replace('/', '-', $this->pageUrl) . '.' . pathinfo($this->pageImages, PATHINFO_EXTENSION);
                    copy($this->pageImages, Yii::app()->basePath . '/../uploads/images/model/' . $image);
                    $this->pageImages = $image;
                }
            }
            $sql = 'SELECT "pageTitle", "pageId" FROM {{pages}} WHERE "pageUrl" = LOWER(\'' . strtolower($this->cat_url . '/' . getUrl::cleanString($this->brand)) . '\') AND "pageParent" = ' . $this->cat_id . ' AND "pageType" = \'brand\'';
            $brand = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryRow();
            if (!empty($brand)) {
                $parent = $brand['pageId'];
            } else {
                $data = array(
                    'pageType' => 'brand',
                    'pageAction' => 'list/brand',
                    'pageParent' => $this->cat_id,
                    'pageUrl' => $this->cat_url . '/' . getUrl::cleanString($this->brand),
                    'pageTitle' => $this->brand
                );
                Yii::app()->db->getCommandBuilder()->createInsertCommand('{{pages}}', $data)->execute();
                $parent = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{pages}}');
            }
            $this->pageParent = $parent;
            return true;
        }
        return FALSE;
    }

    protected function afterDelete() {
        parent::afterDelete();
        if (file_exists("uploads/images/" . $this->pageType . "/" . $this->pageImages) && !empty($this->pageImages)) {
            unlink("uploads/images/" . $this->pageType . "/" . $this->pageImages);
            mTools::clearThumbImages(mTools::findFile('uploads/images/' . $this->pageType . '/thumbs/', pathinfo($file, PATHINFO_FILENAME), 'jpg'));
        }
    }

}
